package com.microservice.wechat.service.impl;

import com.microservice.api.common.Result;
import com.microservice.api.wechat.dto.ArticleEndMd;
import com.microservice.common.utils.WechatTokenUtil;
import com.microservice.wechat.entity.Article;
import com.microservice.wechat.entity.dto.ArticleDTO;
import com.microservice.wechat.entity.dto.DraftAddRequest;
import com.microservice.wechat.entity.dto.DraftAddResponse;
import com.microservice.wechat.mapper.ArticleMapper;
import com.microservice.wechat.service.WechatDraftService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 微信草稿箱服务实现类
 */
@Slf4j
@Service
public class WechatDraftServiceImpl implements WechatDraftService {
    
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ArticleMapper articleMapper;


    @Autowired
    private WechatTokenUtil wechatTokenUtil;
    
    private static final String DRAFT_ADD_URL = "https://api.weixin.qq.com/cgi-bin/draft/add?access_token={accessToken}";
    
    @Override
    public DraftAddResponse addDraft(DraftAddRequest request, String accessToken) {
        try {
            log.info("调用微信新建草稿接口，accessToken: {}", accessToken);
            log.info("请求参数: {}", request);
            
            DraftAddResponse response = restTemplate.postForObject(
                DRAFT_ADD_URL,
                request,
                DraftAddResponse.class,
                accessToken
            );
            
            log.info("微信新建草稿接口响应: {}", response);

            //推送邮件

            return response;
        } catch (Exception e) {
            log.error("调用微信新建草稿接口异常", e);
            DraftAddResponse errorResponse = new DraftAddResponse();
            errorResponse.setErrcode(-1);
            errorResponse.setErrmsg("调用微信接口异常: " + e.getMessage());
            return errorResponse;
        }
    }




    @Override
    public Result<com.microservice.api.wechat.dto.DraftAddResponse> addDraft(Article articleVo) {
        try {
            // 获取Access Token
            String accessToken = wechatTokenUtil.getAccessToken(articleVo.getAppId());

            // 构建草稿请求
            DraftAddRequest request = new DraftAddRequest();
            List<ArticleDTO> dtoList = new ArrayList<>();

            ArticleDTO article = new ArticleDTO();
            article.setArticle_type("article_type");
            article.setTitle(articleVo.getTitle());
            article.setAuthor(articleVo.getAuthor() != null ? articleVo.getAuthor() : "CODE");
            article.setDigest("");
            article.setContent(articleVo.getContent());
            article.setContent_source_url("");
            article.setThumb_media_id(wechatTokenUtil.getCoverId(articleVo.getAppId()));
            article.setNeed_open_comment(1);
            article.setOnly_fans_can_comment(0);
            ArticleEndMd articleEndMd= getArticleEndMd(articleVo.getAppId());
            if(articleEndMd!=null){
                article.setContent(article.getContent().concat(articleEndMd.getContent()));
            }
            dtoList.add(article);

            request.setArticles(dtoList);

            // 调用微信API添加草稿
            DraftAddResponse wechatResponse = addDraft(request, accessToken);

            // 转换为API的DraftAddResponse
            com.microservice.api.wechat.dto.DraftAddResponse response = new com.microservice.api.wechat.dto.DraftAddResponse();
            BeanUtils.copyProperties(wechatResponse, response);

            // 检查微信API返回的错误码
            if (response.getMedia_id() != null) {
                return Result.success(response);
            } else {
                String errorMsg = response.getErrmsg() != null ? response.getErrmsg() : "新建草稿失败";
                return Result.error(errorMsg);
            }
        } catch (Exception e) {
            log.error("新建草稿失败", e);
            return Result.error("新建草稿失败: " + e.getMessage());
        }
    }

    @Override
    public ArticleEndMd getArticleEndMd(String appId) {
        return articleMapper.getArticleEndMd(appId);
    }
}
